require("../models/order.server.model")
var mongoose = require("mongoose");
var responseProtocol = require("../util/responseProtocol");
var OrderModel = mongoose.model("order");
var MerchantModel = mongoose.model("merchant");
var ClientModel = mongoose.model("client");
var Dish = mongoose.model("dish")
var responseConstant = require("../constants/response.server.constant.js");
var async = require("async");
var jmsPublisher = require("../../../jms/jmsPublisher.queue.js");
var moment = require("moment");

function complainOrder(req, res) {
    OrderModel.findOne({_id: req.params.oid}).populate("merchant").populate("client")
        .exec(function (err, order) {
            if (!err) {
                order.complain = req.body.complaint;
                order.save(function (err1) {
                    if (!err1) {
                        jmsPublisher.publishComplaint(order._id, order.merchant._id, order.client._id, function () {
                            res.json(responseProtocol(true, null, null))
                        });
                    }
                    else {
                        res.json(responseProtocol(true, responseConstant.SYSTEM_ERRO, null))
                    }
                });
            }
            else {
                res.json(responseProtocol(true, responseConstant.SYSTEM_ERRO, null))
            }
        });
}

exports.showCurrentOrder = function (req, res) {
    var session = req.session;
    var client = session.client;
    var merchantCart = client.cart[req.params.mid];
    //var merchantCart = [];

    //var client = {caddress: "zhuhai"}
    var currentOrderDetail = {};
    //var dish = new Dish();
    //dish.dname = "test";
    //dish.price = 12;
    //dish.save(function(err, dish){
    //    console.log(dish)
    //});
    currentOrderDetail.sum = 0;
    currentOrderDetail.mid = req.params.mid;
    currentOrderDetail.client = client;
    currentOrderDetail.orderItem = []
    async.each(merchantCart, function (item, callback) {
        Dish.findOne({_id: item.did}, function (err, dish) {
            if (err) {
                callback();
            } else {
                currentOrderDetail.orderItem.push({
                    dish: dish,
                    num: item.num,
                    smallSum: item.num * dish.price
                });
                currentOrderDetail.sum = currentOrderDetail.sum + dish.price * item.num;
                callback();
            }
        })
    }, function (err) {
        if (err) {
            res.json(responseProtocol(false, responseConstant.SYSTEM_ERRO, null));
        } else {
            console.log(currentOrderDetail)
            res.json(responseProtocol(true, null, currentOrderDetail));
        }
    })

}

exports.operateOrder = function (req, res) {
    var action = req.query.action;
    if (action == 1) {
        confirmReceiveOrder(req, res);
    } else if (action == 2) {
        gradeFromHistory(req, res);
    } else if (action == 3) {
        complainOrder(req, res);
    }
}

exports.checkoutOrComfirmOrder = function (req, res) {
    var action = req.query.action;
    if (action == 1) {
        checkoutOrder(req, res);
    } else if (action == 2) {
        comfirmOrder(req, res);
    }
}

//not test
function comfirmOrder(req, res) {
    //res.json(responseProtocol(true, null, null));
    var session = req.session;
    //var session = {}
    //session.carts = {}
    //session.carts[req.params.mid] = {
    //    complain:'hao hao chi'
    //}

    var client = session.client;
    var merchantCart = client.cart[req.params.mid];
    if (merchantCart == null) {
        res.json(responseProtocol(false, responseConstant.CONFIRM_ORDER_FAILD, null))
    }
    delete session.client.cart[req.params.mid];
    var newOrder = new OrderModel();
    var total = 0;
    async.each(merchantCart, function (item, callback) {
        Dish.findOne({_id: item.did}, function (err, dish) {
            if (err) {
                res.json(responseProtocol(false, responseConstant.SYSTEM_ERRO, null));
            } else {
                var smallSum = dish.price * item.num;
                newOrder.orderItem.push({dish: dish, num: item.num, smallSum: smallSum});
                total = total + dish.price * item.num;
            }
            callback();
        })
    }, function (err) {
        if (err) {
            res.json(responseProtocol(true, null, null));
        } else {
            newOrder.merchant = req.params.mid;
            newOrder.client = client._id;
            newOrder.confirm = 0;
            newOrder.status = 0;
            newOrder.grade = -1;
            newOrder.complain = null;
            newOrder.total = total;
            newOrder.save(function (err, order) {
                res.json(responseProtocol(true, null, null));
            })
        }
    });
}

function checkoutOrder(req, res) {
    var session = req.session;
    var client = session.client;
    var merchantCart = client.cart[req.params.mid];

    if (merchantCart == null) {
        res.json(responseProtocol(false, responseConstant.CONFIRM_ORDER_FAILD, null))
    }
    delete session.client.cart[req.params.mid];
    var newOrder = new OrderModel();

    async.each(merchantCart, function (item, callback) {
        Order.findOne({_id: item._id}, function (err, order) {
            newOrder.orderItem.push({dish: item, num: item.num});
        })
    }, function (err) {
        if (err) {
            res.json(responseProtocol(true, null, null));
        } else {
            newOrder.merchant = req.params.mid;
            newOrder.client = client._id;
            newOrder.confirm = 0;
            newOrder.status = 0;
            newOrder.grade = -1;
            newOrder.complain = null;
            //是否塞到session
        }
    });
}

function confirmReceiveOrder(req, res) {
    OrderModel.update({_id: req.params.oid}, {confirm: 1}, function (err, order) {
        if (err) {
            res.json(responseProtocol(false, responseConstant.SYSTEM_ERRO, null))
        } else {
            res.json(responseProtocol(true, null, order));
        }
    })
}

//function gradeFromHistory(req, res) {
//    Order.findOne({_id: req.params.oid}, function (err, order) {
//        if (err) {
//            res.json(responseProtocol(false, responseConstant.SYSTEM_ERRO, null));
//        } else {
//            order.grade = req.params.grade;
//            order.save(function (err) {
//                res.json(responseProtocol(true, null, order));
//            })
//        }
//    })
//}

exports.makeOrderTestData = function (req, res) {
    var merchant = new MerchantModel();
    merchant.mname = "labintest";
    merchant.grade = 3;
    merchant.address = 'zhuhai';
    merchant.mtel = '13631225776';
    merchant.logo = '/img/aaaa';
    merchant.password = '123';
    merchant.dish = [];
    merchant.createDate = '2016-08-22T02:46:15.630Z';
    merchant.save(function (err, merchant) {
        console.log(merchant);
        var dish = new Dish();
        dish.dname = "test";
        dish.price = 12;
        dish.img = "/img/test.jpg"
        dish.save(function (err, dish) {
            var client = new ClientModel();
            client.cname = "labintest";
            client.caddress = "guandong";
            client.save(function (err, client) {
                var order = new OrderModel();
                order.merchant = merchant._id;
                order.complain = "hahahaha"
                order.total = dish.price;
                order.status = 1;
                order.confirm = 1;
                order.grade = -1;
                order.orderItem = [{dish: dish, num: 2, smallSum: dish.price * 2}];
                order.client = '57be796ab3b9f3f823fd2d4e';
                order.total = 123;
                order.save(function (err, order) {
                    console.log(order);
                })
            })

        });
    })
    res.send("sucess")
}

//not test
exports.loadOrder = function (req, res) {
    var session = req.session;
    var client = session.client;
    //------测试
    //var client = {_id: '57be796ab3b9f3f823fd2d4e'}
    //-----------------


    var cb = function (err, orders) {
        if (err) {
            res.json(responseProtocol(false, responseConstant.SYSTEM_ERRO, null))
        } else {
            res.json(responseProtocol(true, null, orders))
        }
    }

    if (req.query.action == 1) {
        OrderModel.find({
            client: client._id,
            confirm: 0,
            //status: {$or: [0, 1]},
            $or: [{status: 0}, {status: 1}]
        }).populate('merchant').sort({createDate: "desc"}).exec(function (err, orders) {
            if (err) {
                res.json(responseProtocol(false, responseConstant.SYSTEM_ERRO, null))
            } else {
                res.json(responseProtocol(true, null, orders))
            }
        })
    } else if (req.query.action == 2) {
        OrderModel.find({
                client: client._id,
                confirm: 1,
                status: 2
            }
        ).populate('merchant').sort({createDate: "desc"}).exec(cb)
    }
};

exports.refreshOrderDetails = function (req, res) {
    var oid = req.params.oid;
    OrderModel.findOne({_id: oid}, function (err, order) {
        if (err) {

        } else {
            res.json({
                msg: 'SUCCESS',
                order: order
            })
        }
    })
};

exports.historyOrder = function (req, res) {
    var session = req.session;
    //-----测试数据
    //session = {};
    //session.client = {_id: '57be796ab3b9f3f823fd2d4e'}
    //-------
    OrderModel.find({
        client: session.client._id,
        $or: [{confirm: 1}, {status: 2}]
    }).populate('merchant').sort({createDate: "desc"}).exec(function (err, orders) {
        res.json(responseProtocol(true, null, orders));
    })
}

function gradeFromHistory(req, res) {
    var grade = req.body.grade;
    var oid = req.params.oid;
    OrderModel.update({_id: oid}, {grade: grade}, function (err, order) {
        if (!err) {
            OrderModel.findOne({_id: oid}).populate("merchant").exec(function (err, order) {
                var grade = order.merchant.grade;
                var createDateObj = {}
                OrderModel.find({merchant: order.merchant._id}, function (err, orders) {
                    for (var i = 0; i < orders.length; i++) {
                        createDateObj[orders[i].createDate] = orders[i].grade;
                    }
                    var curOrderTime = order.createDate;
                    console.log(curOrderTime);
                    var curMgrade;
                    var orderCount = 0;
                    var gradesTotal = 0;
                    var average = 0;
                    var orderGrade = 0;
                    var preOrdersCount = 100;
                    for (var key in createDateObj) {
                        if ((curOrderTime.getTime() - new Date(key).getTime()) <= 1800) {
                            orderGrade = createDateObj[key];
                            if (orderGrade == -1) {
                                orderGrade = 3;
                            }
                            orderCount++;
                            gradesTotal += orderGrade;
                        }
                    }
                    average = gradesTotal / orderCount;
                    curMgrade = (orderCount / (orderCount + preOrdersCount)) * average + (preOrdersCount / (orderCount + preOrdersCount)) * grade
                    curMgrade = curMgrade.toFixed(2)
                    console.log(curMgrade);
                    MerchantModel.update({_id: order.merchant._id}, {grade: curMgrade}, function (err, merchant) {
                        if (curMgrade < 2.5) {
                            jmsPublisher.publishLowGrade(order.merchant._id, function () {
                                //console.log(jms)
                                res.json(responseProtocol(true, null, null));
                            })
                        } else {
                            res.json(responseProtocol(true, null, null));
                        }
                    })
                    //res.json(responseProtocol(true, null, null));
                })
            })
        }
    })

};

exports.orderComplaint = function () {

};

